package com.tanhua.server.service;

import com.tanhua.dubbo.api.TestSoulApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.db.*;
import com.tanhua.model.vo.TestSoulReportVO;
import com.tanhua.model.vo.TestsoulVo;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class TestSoulService {

    private static String TESTSOUL_JUNIOR = "初级灵魂题";
    private static String TESTSOUL_INTERMEDIATE = "中级灵魂题";
    private static String TESTSOUL_SENIOR = "高级灵魂题";

    @DubboReference
    private TestSoulApi testSoulApi;

    @DubboReference
    private UserInfoApi userInfoApi;
    /**
     * 查找问卷
     *
     * @return
     */
    public List<TestsoulVo> testSoul() {
        List<TestsoulVo> vos = new ArrayList<>();
        //调用API查询，查询高级问卷，并将其放入List<TestsoulVo>中
        Testsoul testsoulSenior = testSoulApi.findTestSoul(TESTSOUL_SENIOR,null);
        vos.add(TestsoulVo.init(testsoulSenior));
        //调用API查询，查询中级问卷，并将其放入List<TestsoulVo>中
        Testsoul testsoulIntermediate = testSoulApi.findTestSoul(TESTSOUL_INTERMEDIATE,testsoulSenior);
        vos.add(TestsoulVo.init(testsoulIntermediate));
        //调用API查询，查询初级问卷，并将其放入List<TestsoulVo>中
        Testsoul testsoulJunior = testSoulApi.findTestSoul(TESTSOUL_JUNIOR,testsoulIntermediate);
        vos.add(TestsoulVo.init(testsoulJunior));


        //返回
        return vos;
    }

    /**
     * 用户答卷计算成绩
     * @param answers
     * @return
     */
    public String calculateScore(CalculateScore answers) {
        //调用API进行查询，将数据计算并保存到数据库中，并根据分数设置用户的类型；
        String report = testSoulApi.calculateScore(answers, UserHolder.getUserId());
        //返回报告id
        return report;
    }

    /**
     * 测试用户灵魂信息
     * @param id   报告id
     * @return
     */
    public TestSoulReportVO report(String id) {
        // 1、调用testSoulApi进行查询，，查询用户灵魂类型
        SubmitTheQuestionnaire submitTheQuestionnaire = testSoulApi.findById(id);
        //2、调用testSoulApi进行查询，查询用户灵魂信息
        TestSoulReportVO vo = testSoulApi.report(submitTheQuestionnaire.getUserType(),submitTheQuestionnaire.getAchievement());
        //3、调用testSoulApi进行分页查询，查询用户的type相同的用户id列表
        List<Long> idList = testSoulApi.findSameTypeIds(submitTheQuestionnaire.getUserType());
        // 3、调用UserInfoAPI进行查询，查询用户id和照片
        List<UserInfo> userInfoList = userInfoApi.findSameUserInfo(idList);
        // 4、构建Vo，并返回
        List<SimilarYou> similarYouList = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            similarYouList.add(new SimilarYou(userInfo.getId().intValue(),userInfo.getAvatar()));
        }
        vo.setSimilarYou(similarYouList);
        return vo;
    }
}
